package com.mzba.easy.weibo.ui;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.mzba.easy.weibo.MainActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.UserEntry;
import com.mzba.easy.weibo.db.UserGson;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.BasicUIEvent;
import com.mzba.easy.weibo.util.StringUtil;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
import com.mzba.easy.weibo.widget.CustomListView;
import com.mzba.easy.weibo.widget.RemoteImageView;

/**
 * 
 * @author 06peng
 *
 */
public class FriendsFragment extends SherlockFragment implements BasicUIEvent, Callback {
	
	private CustomListView listview;
	private LinearLayout localView;
	private Handler handler;
	private WeiboManager weiboManager;
	private List<UserEntry> entries;
	private List<UserEntry> moreEntries;
	private int count = 20;
	private int cursor = 0;
	private UserListAdapter adapter;
	
	private final int get_friends = 1;
	private final int refresh_timeline = 2;
	private final int get_more_datas = 3;
	
	private boolean isLoading;
	
	private String userid;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		handler = new Handler(this);
		weiboManager = new WeiboManager(getActivity());
		userid = getArguments().getString("userid");
		UICore.eventTask(this, (MainActivity) getActivity(), get_friends, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_layout, null);
		if (localView != null) {
			localView.removeAllViews();
		}
		localView = (LinearLayout) view.findViewById(R.id.pager);
		if (listview == null) {
			listview = (CustomListView) inflater.inflate(R.layout.listview_layout, null);
		}
		listview.setSelector(R.drawable.list_bg_selector);
		listview.setonRefreshListener(new CustomListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				menuRefresh();
			}
		});
		listview.setonLoadListener(new CustomListView.OnLoadListener() {
			
			@Override
			public void onLoad() {
				UICore.eventTask(FriendsFragment.this, (MainActivity) getActivity(), get_more_datas, null);
			}
		});
		listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (arg2 == adapter.getCount()) {
					return;
				}
				UserEntry entry = entries.get(arg2 - 1);
				if (entry != null) {
					Intent intent = new Intent(getActivity(), UserinfoActivity.class);
					intent.putExtra("userid", entry.getId());
					startActivity(intent);
				}
			}
		});
		return view;
	}
	
	public void menuRefresh() {
		cursor = 0;
		UICore.eventTask(FriendsFragment.this, (MainActivity) getActivity(), refresh_timeline, null);
	}

	@Override
	public void execute(int mes, Object obj) {
		try {
			switch (mes) {
			case get_friends:
				isLoading = false;
				if (StringUtil.isBlank(userid)) {
					userid = AppContext.getInstance().getUid();
				}
				UserGson gson =  weiboManager.getFriends(userid, count, cursor);
				entries = gson.getUsers();
				cursor = gson.getNext_cursor();
				handler.sendEmptyMessage(get_friends);
				break;
			case refresh_timeline:
				isLoading = false;
				if (StringUtil.isBlank(userid)) {
					userid = AppContext.getInstance().getUid();
				}
				UserGson gson2 =  weiboManager.getFriends(userid, count, cursor);
				entries = gson2.getUsers();
				cursor = gson2.getNext_cursor();
				handler.sendEmptyMessage(refresh_timeline);
				break;
			case get_more_datas:
				if (StringUtil.isBlank(userid)) {
					userid = AppContext.getInstance().getUid();
				}
				UserGson gson3 =  weiboManager.getFriends(userid, count, cursor);
				moreEntries = gson3.getUsers();
				cursor = gson3.getNext_cursor();
				entries.addAll(moreEntries);
				handler.sendEmptyMessage(get_more_datas);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case get_friends:
			isLoading = true;
			if (entries != null && !entries.isEmpty()) {
				adapter = new UserListAdapter();
				listview.setAdapter(adapter);
			}
			listview.onRefreshComplete();
			break;
		case refresh_timeline:
			isLoading = true;
			adapter.notifyDataSetChanged();
			listview.onRefreshComplete();
			break;
		case get_more_datas:
			adapter.notifyDataSetChanged();
			listview.onLoadComplete();
			listview.setSelection(entries.size() - count);
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (isLoading) {
			((MainActivity) getActivity()).loadFinish();
		} else {
			((MainActivity) getActivity()).loading();
		}
		localView.removeAllViews();
		localView.addView(listview);
	}
	
	public class UserListAdapter extends BaseAdapter {
		
		@Override
		public int getCount() {
			return entries.size();
		}

		@Override
		public Object getItem(int position) {
			return entries.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView != null && convertView.getId() == R.id.friend_item_layout) {
				holder = (ViewHolder) convertView.getTag();
			} else {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(getActivity()).inflate(R.layout.friend_item, null);
				holder.addView = (TextView) convertView.findViewById(R.id.friend_button);
				holder.avatarView = (RemoteImageView) convertView.findViewById(R.id.iv_author_photo);
				holder.detailView = (TextView) convertView.findViewById(R.id.detail);
				holder.followerView = (TextView) convertView.findViewById(R.id.fullowers);
				holder.friendView = (TextView) convertView.findViewById(R.id.friends);
				holder.locationView = (TextView) convertView.findViewById(R.id.userlocation);
				holder.sexView = (ImageView) convertView.findViewById(R.id.usersex);
				holder.usernameView = (TextView) convertView.findViewById(R.id.username);
				holder.weiboView = (TextView) convertView.findViewById(R.id.weibo);
				convertView.setTag(holder);
			}
			UserEntry entry = entries.get(position);
			if (entry != null) {
				holder.avatarView.setDefaultImage(R.drawable.avatar_default_big);
				holder.avatarView.setImageUrl(entry.getProfile_image_url(), AppContext.USERHEADICON, position, listview);
			}
			if (StringUtil.isNotBlank(entry.getDescription())) {
				holder.detailView.setVisibility(View.VISIBLE);
				holder.detailView.setText(entry.getDescription());
			} else {
				holder.detailView.setVisibility(View.GONE);
			}
			holder.followerView.setText(Html.fromHtml("粉丝&nbsp;<font color=#419AD9>" + entry.getFollowers_count() + "</font>"));
			holder.friendView.setText(Html.fromHtml("关注&nbsp;<font color=#419AD9>" + entry.getFriends_count() + "</font>"));
			holder.weiboView.setText(Html.fromHtml("微博&nbsp;<font color=#419AD9>" + entry.getStatuses_count() + "</font>"));
			holder.locationView.setText(entry.getLocation());
			if (entry.getGender().equals("m")) {
				holder.sexView.setImageDrawable(getResources().getDrawable(R.drawable.user_info_male));
			} else if (entry.getGender().equals("f")) {
				holder.sexView.setImageDrawable(getResources().getDrawable(R.drawable.user_info_female));
			}
			holder.usernameView.setText(entry.getScreen_name());
			if (entry.isFollow_me() && entry.isFollowing()) {
				holder.addView.setText("互相关注");
			} else {
				if (entry.isFollow_me()) {
					holder.addView.setText("粉丝");
				} else {
					holder.addView.setText("非粉丝");
				}
			}
			return convertView;
		}
		
	}
	
	public static class ViewHolder {
		RemoteImageView avatarView;
		TextView usernameView;
		ImageView sexView;
		TextView locationView;
		TextView friendView;
		TextView followerView;
		TextView weiboView;
		TextView detailView;
		TextView addView;
	}
	
}
